package com.jt.www.admin.user.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jt.www.admin.user.service.UserListFormService;
import com.jt.www.model.remote.user.UserListDownloadVo;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.EduOrgListVO;
import com.jt.www.model.vo.EduOrgsVO;
import com.jt.www.model.vo.UserInfoVo;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import com.jt.www.util.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "查询,下载用户列表", tags = {"USERLIST-API"}, description = "导出用户列表接口")
@RestController
@RequestMapping(value = "/user/v1")
public class UserListFormController {
    public static final Logger log = LoggerFactory.getLogger(UserListFormController.class);
    @Autowired
    private UserListFormService userlistFormService;

    @ApiOperation(value = "导出用户信息列表", notes = "统计结果并下载")
    @GetMapping(value = "/downUserList")
    public void downAppList(HttpServletResponse response, UserInfoVo userInfoVo) {

        try {

            String findCode = "downUserList_" + System.currentTimeMillis();

            log.info("{} 导出用户信息列表 入参：userInfoVo->{}", findCode, JsonUtil.object2Json(userInfoVo));

            // 查询需要导出的数据
            List<UserListDownloadVo> list = userlistFormService.downUserList(userInfoVo);

            // 构造导出数据结构
            String titles = "序号,用户账号,用户名,学校/企业名称,组织机构代码,注册时间,用户类型,用户角色,学校类型";  // 设置表头
            String keys = "serialNo,userLoginId,name,custFullName,bl,createTime,orgType,personType,schoolType";  // 设置每列字段

            // 构造导出数据
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> map = null;

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    map = new HashMap<>();
                    map.put("serialNo", i + 1);
                    map.put("userLoginId", StringUtils.isNotBlank(list.get(i).getUserLoginId()) ? list.get(i).getUserLoginId() + "\t" : "");
                    map.put("name", StringUtils.isNotBlank(list.get(i).getName()) ? list.get(i).getName() : "");
                    map.put("custFullName", StringUtils.isNotBlank(list.get(i).getCustFullName()) ? list.get(i).getCustFullName() : "");
                    map.put("bl", StringUtils.isNotBlank(list.get(i).getBl()) ? list.get(i).getBl() + "\t" : "");
                    map.put("createTime", list.get(i).getCreateTime());
                    map.put("orgType", StringUtils.isNotBlank(list.get(i).getOrgType()) ? list.get(i).getOrgType() : "");
                    map.put("personType", StringUtils.isNotBlank(list.get(i).getPersonType()) ? list.get(i).getPersonType() : "");
                    map.put("schoolType", StringUtils.isNotBlank(list.get(i).getSchoolType()) ? list.get(i).getSchoolType() : "");

                    datas.add(map);
                }
            }

            // 设置导出文件前缀
            String fName = "用户信息_";

            // 文件导出
            OutputStream os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fName, response);
            CsvExportUtil.doExport(datas, titles, keys, os);
            os.close();
        } catch (Exception e) {
            log.error("用户信息 导出失败" + e.getMessage(), e);
        }
    }

    /**
     * 查询机构信息列表
     */
    @ApiOperation(value = "查询机构信息列表", notes = "查询机构信息列表", httpMethod = "POST")
    @PostMapping(value = "/queryOrgInfoList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<EduOrgsVO>> queryOrgInfoList(@RequestBody EduOrgListVO eduOrgListVO) {
        return userlistFormService.queryOrgInfoList(eduOrgListVO);
    }

    /**
     * 导出机构列表
     *
     * @return void
     * @Author xq.wu
     * @Date 14:23 2019/11/11
     * @Param [userInfoVo, response, request]
     */
    @ApiOperation(value = "导出机构信息列表", notes = "统计结果并下载")
    @GetMapping(value = "/downOrgList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downOrgList(EduOrgListVO eduOrgListVO, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            //导出
            eduOrgListVO.setIsDownload(1);
            String findCode = "EDU_ORG :" + System.currentTimeMillis();
            log.debug(findCode + "前端传递参数 ，{}", JSON.toJSONString(eduOrgListVO));
            List orgList = userlistFormService.queryOrgInfoList(eduOrgListVO).getBody().getList();

            ExcelUtils.checkNull(orgList);
            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("items", orgList);

            //模板位置
            String path = "excel/templates/orglist.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);
            String fileName = "机构列表.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
